package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.service.ExcelDeduplicationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel去重控制器
 * 提供文件上传、去重、导出功能
 */
@Slf4j
@RestController
@RequestMapping("/excel")
@CrossOrigin(origins = "*")
public class ExcelDeduplicationController {

    private static final Logger log = LoggerFactory.getLogger(ExcelDeduplicationController.class);

    @Autowired
    private ExcelDeduplicationService excelDeduplicationService;

    /**
     * 上传Excel文件并去重
     * POST /excel/deduplicate
     * Content-Type: multipart/form-data
     * 
     * @param file 上传的Excel文件
     * @return 处理结果
     */
    @PostMapping("/deduplicate")
    public ResponseEntity<Map<String, Object>> deduplicateExcel(@RequestParam("file") MultipartFile file) {
        log.info("收到Excel去重请求，文件名: {}, 大小: {} bytes", 
            file.getOriginalFilename(), file.getSize());

        try {
            Map<String, Object> result = excelDeduplicationService.processExcelDeduplication(file);
            
            if ((Boolean) result.get("success")) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("Excel去重处理异常", e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("error", "处理失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }

    /**
     * 获取输出文件列表
     * GET /excel/files
     * 
     * @return 输出文件列表
     */
    @GetMapping("/files")
    public ResponseEntity<Map<String, Object>> getOutputFiles() {
        try {
            List<Map<String, Object>> fileList = excelDeduplicationService.getOutputFiles();
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("files", fileList);
            result.put("count", fileList.size());
            result.put("message", String.format("找到 %d 个输出文件", fileList.size()));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取输出文件列表异常", e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("error", "获取文件列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }

    /**
     * 获取服务信息
     * GET /excel/info
     * 
     * @return 服务信息
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getServiceInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("service", "Excel去重服务");
        info.put("version", "1.0.0");
        info.put("description", "Excel文件上传、手机号去重、导出功能");
        
        Map<String, Object> endpoints = new HashMap<>();
        endpoints.put("POST /excel/deduplicate", "上传Excel文件并去重");
        endpoints.put("GET /excel/files", "获取输出文件列表");
        endpoints.put("GET /excel/info", "获取服务信息");
        info.put("endpoints", endpoints);
        
        Map<String, Object> features = new HashMap<>();
        features.put("支持格式", "Excel文件(.xlsx, .xls)");
        features.put("去重规则", "按手机号去重，保留第一条记录");
        features.put("输出位置", "output/excel_dedup/ 目录");
        features.put("文件大小限制", "50MB");
        features.put("手机号识别", "自动识别'手机号'、'phone'、'mobile'等字段");
        info.put("features", features);
        
        Map<String, Object> usage = new HashMap<>();
        usage.put("步骤1", "使用Postman或其他工具上传Excel文件到 /excel/deduplicate");
        usage.put("步骤2", "系统自动按手机号去重并导出到本地文件夹");
        usage.put("步骤3", "通过 /excel/files 接口查看生成的文件列表");
        usage.put("步骤4", "从 output/excel_dedup/ 目录下载去重后的文件");
        info.put("usage", usage);
        
        return ResponseEntity.ok(info);
    }

    /**
     * 健康检查
     * GET /excel/health
     * 
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "Excel去重服务");
        health.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(health);
    }
}
